// pz - 补零
function pz(val, len = 2) {
  val = val + ''
  if (!val) {
    return val
  }
  if (String(val).length >= len) {
    return val
  }
  return `${new Array(len - 1).fill('0').join('')}${val}`
}

// hash - 时间戳
const _t = new Date()
const _hash =
  '' +
  _t.getFullYear() +
  pz(_t.getMonth() + 1) +
  pz(_t.getDate()) +
  pz(_t.getHours()) +
  pz(_t.getMinutes()) +
  pz(_t.getSeconds()) +
  pz(_t.getMilliseconds(), 3)

// 注入 - script/暂不可用
function injectScript() {
  // eslint-disable-next-line quotes
  return `<script>console.log('inject script')</script>`
}

// wmda - 埋点
function injectWMDASdk(extendConfig) {
  const hashParam = {
    ...extendConfig
  }

  const _WMDATempStr = `
  <script type="text/javascript">
    window.WMDA_SDK_CONFIG = {
      api_v: 1,
      sdk_v: 0.1,
      mode: 'report',
      appid: ${hashParam.appid}, 
      key: '${hashParam.key}',   
      project_id: '${hashParam.project_id}',
      cookie_domain: document.domain,
      cate_id: '',
      page_extra: [
        {
          key: '',
          value: ''
        }
      ],
      user_extra: [
        {
          key: '',
          value: ''
        }
      ],
      channel: '', //按需填写
      getUserId: function () {}, //按需填写
      getDeviceId: function () {}, //按需填写
      SPA_HASH: true, //单页应用必选
    }
  </script>
  <script type="text/javascript" src="https://j1.58cdn.com.cn/wmda/js/statistic.js?v=epfe"></script>`

  return _WMDATempStr
}

// beidou - 上报
function injectBeidouSdk(extendConfig) {
  const hashParam = {
    ...extendConfig
  }

  const _BeidouTempStr = `
  <script type="text/javascript" src="https://j1.58cdn.com.cn/beidou-sdk/browser/bundle.min.js?v=epfe"></script>
  <script type="text/javascript">
    window.onload = function () {
      window.Beidou && window.Beidou.init({
        beforeSend(event) {
          const { apis } = event
          if (Array.isArray(apis) && +apis[0].statusCode === 302) {
            return null
          }
          return event
        },
        isProd: !!window.location.host.includes('58corp'), 
        overtime: ${hashParam.overtime},   
        projectId: ${hashParam.projectId}
      })
    }
    </script>`

  return _BeidouTempStr
}

module.exports = {
  _hash,
  injectScript,
  injectWMDASdk,
  injectBeidouSdk
}
